<template>
  <!-- 条件查询 -->
    <div style="border: 1px solid #ccc;padding: 20px; margin: 10px;">
      申请人:<el-input v-model="page.UserName" style="width: 200px;"></el-input>
      请假时间:<el-date-picker
                v-model="page.StartTime"
                type="date"
                clearable
                placeholder="请假时间"
              />
              至
              <el-date-picker
                v-model="page.EndTime"
                type="date"
                clearable
                placeholder="结束时间"
              />
      审批状态: 
      <el-select v-model="page.Status"placeholder="选择状态" style="width: 200px;" clearable>
        <el-option label="待审批" :value="false" />
        <el-option label="已审批" :value="true" />
      </el-select>
      <el-button type="primary" @click="Getapproval">查询</el-button>
      <el-button type="danger" @click="clear">重置</el-button>
    </div>
     <div style="border: 1px solid #ccc;padding: 20px; margin: 10px;">
      <el-button type="success" v-if="pinia.account.UserName!='张三'"  @click="Addapproval">请假申请</el-button>
    <el-table :data="tableData" style="width: 100%" border>
    <el-table-column fixed type="index" label="序号" width="150" />
    <el-table-column prop="userName" label="姓名" width="120" />
    <el-table-column prop="deparmentName" label="部门" width="120" />
    <el-table-column prop="leaveTypeName" label="请假类别" width="120" />
    <el-table-column prop="startTime" label="请假时间" width="200" >
      <template #default="scope">
        {{moment(scope.row.startTime).format("YYYY-MM-DD")}}至{{moment(scope.row.endTime).format("YYYY-MM-DD")}}
      </template>
    </el-table-column>
    <el-table-column prop="hours" label="总工时" width="120" >
      <template #default="scope">
        {{scope.row.hours}}小时
      </template>
    </el-table-column>
    <el-table-column prop="endTime" label="报到时间" width="180">
      <template #default="scope">
          {{moment(scope.row.endTime).format("YYYY-MM-DD")}}
      </template>
    </el-table-column>
    <el-table-column prop="reason" label="请假事由" width="120" />
    <el-table-column prop="approvaler" label="部门领导" width="120" />
    <el-table-column prop="status" label="审批状态" width="120" >
      <template #default="scope">
          <el-tag type="primary" v-if="scope.row.status==false">待审批</el-tag>
          <el-tag type="warning" v-if="scope.row.status==true">已审批</el-tag>
      </template>
    </el-table-column>
     <el-table-column prop="yeNo" v-if="!IsLeader"  label="审批结果" width="120" >
      <template #default="scope">
          <el-tag type="success" v-if="scope.row.yeNo==false">通过</el-tag>
          <el-tag type="danger" v-if="scope.row.yeNo==true">驳回</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="remark" v-if="!IsLeader" label="审批意见" width="120" />
    <el-table-column prop="createTime" label="创建时间" width="180" >
      <template #default="scope">
          {{moment(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss")}}
      </template>
    </el-table-column>
    
    <el-table-column fixed="right" label="操作" min-width="150">
      <template #default="scope">
        <el-button link type="danger" size="small" v-if="scope.row.status==false" @click="remove(scope.row.id)">删除 </el-button>
        <el-button link type="primary" size="small" v-if="scope.row.status==false" @click="Update(scope.row)">修改</el-button>
        <el-button link type="primary" size="small" v-if="IsLeader && scope.row.status!=true"   @click="Approval(scope.row)">审批</el-button>
      </template>
    </el-table-column>
  </el-table>
  <table>
    <tr>
      <td>
        <el-pagination
          v-model:current-page="page.pageindex"
          v-model:page-size="page.pagesize"
          :page-sizes="[15, 16, 17, 18]"
          layout="slot, sizes, prev, pager, next, jumper"
          :total="page.TotalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          prev-text="上一页"
          next-text="下一页"
        >共{{page.TotalCount}}条 当前第{{page.pageindex}}页/共{{page.TotalPage}}页</el-pagination>
      </td>
    </tr>
  </table>
  <!-- 请假单新增 -->
  <el-dialog v-model="dialogVisible"title="请假申请单"width="800">
     <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="用户名" prop="userId">
      <el-input v-model="ruleForm.userName" disabled/>
    </el-form-item>
     <el-form-item label="部门" prop="deparmentId">
      <el-select v-model="ruleForm.deparmentId " placeholder="Activity zone"disabled>
          <el-option label="IT信息部" :value="1" />
        <el-option label="人力资源部" :value="2" />
        <el-option label="销售部" :value="3" />
        <el-option label="财务部" :value="4" />
      </el-select>
    </el-form-item>
    <el-form-item label="请假类别" prop="leaveType">
      <el-radio-group v-model="ruleForm.leaveType">
        <el-radio v-for="item in leaveType" :label="item.id">{{item.leaveName}}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="请假时间" prop="startTime">
        <el-row align="middle">
          <el-col :span="10">
            <el-date-picker
              v-model="ruleForm.startTime"
              type="date"
              placeholder="开始时间"
              clearable
              style="width: 100%;"
              @click="caleDays"
            />
          </el-col>
          <el-col :span="2" style="text-align: center;">至</el-col>
          <el-col :span="10">
            <el-date-picker
              v-model="ruleForm.endTime"
              type="date"
              placeholder="结束时间"
              clearable
              style="width: 100%;"
               @click="caleDays"
            />
          </el-col>
        </el-row>
  </el-form-item>
    <el-form-item label="总工时(8时/天)" prop="hours">
      <el-input v-model="ruleForm.hours" style="width: 200px;" disabled/>
    </el-form-item>
   <el-form-item label="报道时间">
      <el-date-picker
        v-model="ruleForm.endTime"
        type="date"
        placeholder="Pick a date"
        clearable
      />
    </el-form-item>
    <el-form-item label="请假事由" prop="reason">
      <el-input v-model="ruleForm.reason" type="textarea" />
    </el-form-item>
     <el-form-item label="部门领导" prop="userId">
      <el-input v-model="ruleForm.approvaler"  disabled/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        提交
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
  <!--修改请假申请  -->
  <el-dialog v-model="UPdialogVisible"title="修改申请单"width="800">
     <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="用户名" prop="userId">
      <el-input v-model="ruleForm.userName" disabled/>
    </el-form-item>
     <el-form-item label="部门" prop="deparmentId">
      <el-select v-model="ruleForm.deparmentId " placeholder="Activity zone"disabled>
          <el-option label="IT信息部" :value="1" />
        <el-option label="人力资源部" :value="2" />
        <el-option label="销售部" :value="3" />
        <el-option label="财务部" :value="4" />
      </el-select>
    </el-form-item>
    <el-form-item label="请假类别" prop="leaveType">
      <el-radio-group v-model="ruleForm.leaveType">
        <el-radio v-for="item in leaveType" :label="item.id">{{item.leaveName}}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="请假时间" prop="leaveType">
        <el-row align="middle">
          <el-col :span="10">
            <el-date-picker
              v-model="ruleForm.startTime"
              type="date"
              placeholder="开始时间"
              clearable
              style="width: 100%;"
              @click="caleDays"
            />
          </el-col>
          <el-col :span="2" style="text-align: center;">至</el-col>
          <el-col :span="10">
            <el-date-picker
              v-model="ruleForm.endTime"
              type="date"
              placeholder="结束时间"
              clearable
              style="width: 100%;"
               @click="caleDays"
            />
          </el-col>
        </el-row>
  </el-form-item>
    <el-form-item label="总工时(8时/天)" prop="hours">
      <el-input v-model="ruleForm.hours" style="width: 200px;" disabled/>
    </el-form-item>
   <el-form-item label="报道时间">
      <el-date-picker
        v-model="ruleForm.endTime"
        type="date"
        placeholder="Pick a date"
        clearable
      />
    </el-form-item>
    <el-form-item label="请假事由" prop="reason">
      <el-input v-model="ruleForm.reason" type="textarea" />
    </el-form-item>
     <el-form-item label="部门领导" prop="approvaler">
      <el-input v-model="ruleForm.approvaler" disabled/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="UpsubmitForm(ruleFormRef)">
        更新
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
  <!--审批申请单  -->
  <el-dialog v-model="AppdialogVisible"title="申请单审批"width="800">
     <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="用户名" prop="userName">
      <el-input v-model="ruleForm.userName" disabled/>
    </el-form-item>
     <el-form-item label="部门" prop="deparmentId">
      <el-select v-model="ruleForm.deparmentId " placeholder="Activity zone"disabled>
          <el-option label="IT信息部" :value="1" />
        <el-option label="人力资源部" :value="2" />
        <el-option label="销售部" :value="3" />
        <el-option label="财务部" :value="4" />
      </el-select>
    </el-form-item>
    <el-form-item label="请假类别" prop="leaveType">
      <el-radio-group v-model="ruleForm.leaveType" disabled>
        <el-radio v-for="item in leaveType" :label="item.id">{{item.leaveName}}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="请假时间" prop="leaveType">
        <el-row align="middle">
          <el-col :span="10">
            <el-date-picker
              v-model="ruleForm.startTime"
              type="date"
              placeholder="开始时间"
              clearable
              style="width: 100%;"
              @click="caleDays"
              disabled
            />
          </el-col>
          <el-col :span="2" style="text-align: center;">至</el-col>
          <el-col :span="10">
            <el-date-picker
              v-model="ruleForm.endTime"
              type="date"
              placeholder="结束时间"
              clearable
              style="width: 100%;"
               @click="caleDays"
               disabled
            />
          </el-col>
        </el-row>
  </el-form-item>
    <el-form-item label="总工时(8时/天)" prop="hours">
      <el-input v-model="ruleForm.hours" style="width: 200px;" disabled/>
    </el-form-item>
   <el-form-item label="报道时间">
      <el-date-picker
        v-model="ruleForm.endTime"
        type="date"
        placeholder="Pick a date"
        clearable
        disabled
      />
    </el-form-item>
    <el-form-item label="请假事由" prop="reason">
      <el-input v-model="ruleForm.reason" type="textarea" disabled/>
    </el-form-item>
     <el-form-item label="审核" prop="yeNo">
      <!-- <el-input v-model="ruleForm.approvaler" /> -->
      <el-radio-group v-model="ruleForm.yeNo">
      <el-radio :value="false" size="large">通过</el-radio>
      <el-radio :value="true" size="large">驳回</el-radio>
    </el-radio-group>
    </el-form-item>
    <el-form-item label="审批意见" prop="remark" v-if="ruleForm.yeNo==true" >
      <el-input v-model="ruleForm.remark" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="AppsubmitForm(ruleFormRef)">
        提交
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
    </div>
</template>

<script setup lang="ts">
import axios from 'axios'
import moment  from 'moment'
import {ref,reactive, onMounted, useId,nextTick,watch}from 'vue'
import {useCounterStore} from '@/stores/counter'
const pinia=useCounterStore();
import { ElMessage, type FormInstance, type FormRules,ElMessageBox } from 'element-plus'
import { id } from 'element-plus/es/locales.mjs';
import { Read,Write } from '@/http/interceptors'

//#region 获取审批列表
const tableData=ref([])
const page=reactive({
  pageindex:1,
  pagesize:15,
  UserId:'',
  UserName:"",
  StartTime:"",
  EndTime:"",
  Status:null,
  TotalCount:0,
  TotalPage:0,
})

onMounted(()=>{
  Getapproval();
  GetLeave();
})
const Getapproval=()=>{
  page.UserId=pinia.account.UserId
  Read.get("/api/ApprovalGetApprovalList",{params:page}).then(res=>{
    tableData.value=res.data.pageData
    page.TotalCount=res.data.totalCount
    page.TotalPage=res.data.totalPage
  
  })
}
//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  page.pagesize=val
  Getapproval();
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  page.pageindex=val
  Getapproval();
}
//重置
const clear=()=>{
  page.UserId='',
  page.StartTime="",
  page.EndTime="",
  page.Status=null
  Getapproval();
}
//#endregion

//#region  用登录Id获取部们信息
//声明类型
interface Department {
      "id": number,
      "header": string,
      "deparmentName":string
}
const IsLeader=ref(false)//定义bool属性字段
const DepData = ref<Department[]>([])//部门数据
  Read.get("/api/ApprovalGetDeparment",{params:{Uid:pinia.account.UserId}}).then(res=>{
    DepData.value=res.data.data
    console.log(DepData.value)
    //判断登录人是否是部门领导人
      IsLeader.value = DepData.value.some(dept => 
      dept.header ==pinia.account.UserName
    )
  })
//#endregion

//#region   获取请假类型
const leaveType=ref<any>([])
const GetLeave=()=>{
  Read.get("/api/ApprovalGetLeave",{}).then(res=>{
    leaveType.value=res.data.data
  })
}
//#endregion

//#region  计算日期
const caleDays=()=>{
  const start =moment(ruleForm.startTime)
  const end =moment(ruleForm.endTime)
  const days=end.diff(start, 'day')
  ruleForm.hours= days*8
}
//#endregion

//#region 审批新增
//弹窗
const dialogVisible = ref(false)

//新增按钮方法
const Addapproval=()=>{
dialogVisible.value=true;  //打开弹窗
//清空
ruleForm.leaveType=0,
 ruleForm.reason= "",
 ruleForm.startTime= "",
ruleForm.endTime= "",
 ruleForm.hours= 0,
 ruleForm.approvaler= "",
ruleForm.remark= ""
//反填值
ruleForm.userId=pinia.account.UserId
ruleForm.userName=pinia.account.UserName  //反填用户名

ruleForm.deparmentId = DepData.value[0].id//反填部门信息
ruleForm.approvaler=DepData.value[0].header//反填部门领导

//如果是部门领导人,则领导人为张三(董事长)
if(ruleForm.userName==ruleForm.approvaler)
{
  ruleForm.approvaler="张三"
}
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  "userId": '',
  "userName":'',
  "deparmentId": 0,
  "leaveType":0,
  "reason": "",
  "startTime": "",
  "endTime": "",
  "hours": 0,
  "approvaler": "",
  "status": false,
   "yeNo": null,
  "remark": ""
})

//监听日期变化自动赋值
watch(
  () => [ruleForm.startTime, ruleForm.endTime],
  caleDays
)

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  remark: [
    { required: true, message: '审批意见不能为空', trigger: 'blur' },
  ],
   leaveType: [
    {  required: true, message: '请假类型必选', trigger: 'change' },
  ],
  reason: [
    { required: true, message: '请假原因不能为空不能为空', trigger: 'blur' },
    { min: 3, max: 140, message: '请假事由只能3-140个字符', trigger: 'blur' },
  ],
  yeNo: [
    { required: true, message: '审核操作必选', trigger: 'change' },
  ],
  startTime: [
    { required: true, message: '请假时间必选', trigger: 'change' },
  ],
  
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      Write.post("/api/ApprovalCreateApproval",ruleForm).then(res=>{
        console.log(ruleForm)
        if(res.data.code==200)
        {
              dialogVisible.value=false
              ruleForm.leaveType=0,
               ruleForm.reason= "",
               ruleForm.startTime= "",
               ruleForm.endTime= "",
               ruleForm.hours= 0,
               ruleForm.approvaler= "",
               ruleForm.remark= ""
               Getapproval();
          ElMessage.success(res.data.message)
        }
        else
        {
           ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//#endregion

//#region  删除
const remove=(id:any)=>{
 ElMessageBox.confirm(
    '确认删除吗?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      Write.delete("/api/ApprovalDeleteApproval",{params:{Id:id}}).then(res=>{
        if(res.data.code==200)
        {
          ElMessage.success(res.data.message)
          Getapproval();
        }
        else
        {
          ElMessage.error(res.data.message)
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}
//#endregion

//#region  修改
const UPdialogVisible=ref(false)
const Update=(row:any)=>{
   UPdialogVisible.value=true
   Object.assign(ruleForm,row)
}


const UpsubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      Write.put("/api/ApprovalUpdateApproval",ruleForm).then(res=>{
        console.log(ruleForm)
        if(res.data.code==200)
        {
              UPdialogVisible.value=false
              ruleForm.leaveType=0,
               ruleForm.reason= "",
               ruleForm.startTime= "",
               ruleForm.endTime= "",
               ruleForm.hours= 0,
               ruleForm.approvaler= "",
               ruleForm.remark= ""
               Getapproval();
          ElMessage.success(res.data.message)
        }
        else
        {
           ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//#endregion


//#region  审批

const AppdialogVisible=ref(false)
const Approval=(row:any)=>{
AppdialogVisible.value=true
Object.assign(ruleForm,row)
}

const AppsubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      ruleForm.status=true;
      Write.put("/api/ApprovalUpdateApproval",ruleForm).then(res=>{
        console.log(ruleForm)
        if(res.data.code==200)
        {
              UPdialogVisible.value=false
               Getapproval();
          ElMessage.success(res.data.message)
        }
        else
        {
           ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//#endregion
</script>

<style scoped>

</style>